package com.htthorizon.powersupply.controller;

import cn.hutool.core.date.DatePattern;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.htthorizon.powersupply.domain.TgLoadMonitor;
import com.htthorizon.powersupply.service.TgLoadMonitorService;
import com.htthorizon.powersupply.utils.OrgUtil;
import com.htthorizon.powersupply.utils.R;
import com.htthorizon.powersupply.utils.TimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Brilliant
 */
@RestController
@RequestMapping("/tgLoadMonitor")
public class TgLoadMonitorController {

    @Autowired
    private TgLoadMonitorService tgLoadMonitorService;

    @GetMapping("/getRealTime")
    public R<List<TgLoadMonitor>> getLoad(@RequestParam("zbflag") boolean zbflag, @RequestParam(required = false, value = "loadType") String loadType) {
        String dateDt = DatePattern.PURE_DATE_FORMAT.format(new Date());
        Integer time = TimeUtil.getPre_2_TimeIndex();
        String tgType;
        if (zbflag){
            tgType = "专变";
        }else {
            tgType = "公变";
        }
        if (StringUtils.isNotEmpty(loadType) && "预重载".equals(loadType)) {
            List<TgLoadMonitor> list = tgLoadMonitorService.getRealTimeLoad(dateDt,time, tgType, loadType);
            return R.ok(list);
        } else {
            List<TgLoadMonitor> list = tgLoadMonitorService.getRealTimeLoad(dateDt,time, tgType, null);
            return R.ok(list);
        }


    }


    @GetMapping("/getToday")
    public R<List<TgLoadMonitor>> getToday(@RequestParam("zbflag") boolean zbflag, @RequestParam(required = false, value = "loadType") String loadType) {
        LambdaQueryWrapper<TgLoadMonitor> queryWrapper = new LambdaQueryWrapper<>();
        String dateDt = DatePattern.PURE_DATE_FORMAT.format(new Date());
        queryWrapper.eq(TgLoadMonitor::getDataDt, dateDt);
        if (zbflag){
            queryWrapper.eq(TgLoadMonitor::getTgType, "专变");
        }else {
            queryWrapper.eq(TgLoadMonitor::getTgType, "公变");
        }
        if (StringUtils.isNotEmpty(loadType) && "预重载".equals(loadType)) {
//            queryWrapper.like(TgLoadMonitor::getLoadType, "预重载");
        } else {
            //默认不包含预重载
            queryWrapper.notLike(TgLoadMonitor::getLoadType, "预重载");
        }
        List<TgLoadMonitor> list = tgLoadMonitorService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            List<TgLoadMonitor> result = getTgLoadMonitors(list);
            return R.ok(result);
        } else {
            return R.ok(new ArrayList<>());
        }
    }

    @GetMapping("/getAll")
    public R<List<TgLoadMonitor>> getAll(@RequestParam("zbflag") boolean zbflag, @RequestParam(required = false, value = "loadType") String loadType) {
        List<TgLoadMonitor> result = new ArrayList<>();
        LambdaQueryWrapper<TgLoadMonitor> queryWrapper = new LambdaQueryWrapper<>();
        if (zbflag){
            queryWrapper.eq(TgLoadMonitor::getTgType, "专变");
        }else {
            queryWrapper.eq(TgLoadMonitor::getTgType, "公变");
        }
        if (StringUtils.isNotEmpty(loadType) && "预重载".equals(loadType)) {
//            queryWrapper.eq(TgLoadMonitor::getLoadType, loadType);
        } else {
            //默认不包含预重载
            queryWrapper.notLike(TgLoadMonitor::getLoadType, "预重载");
        }
        queryWrapper.ge(TgLoadMonitor::getDataDt, "20250128");
        queryWrapper.ge(TgLoadMonitor::getTime,73);
        queryWrapper.or().gt(TgLoadMonitor::getDataDt, "20250128");
        List<TgLoadMonitor> list = tgLoadMonitorService.list(queryWrapper);
        Map<String, List<TgLoadMonitor>> dateMap = list.stream().collect(Collectors.groupingBy(TgLoadMonitor::getDataDt));
        dateMap.forEach((key, value) -> {
            if (CollectionUtils.isNotEmpty(value)) {
                List<TgLoadMonitor> perDayResult = getTgLoadMonitors(value);
                result.addAll(perDayResult);
            }
        });

        for (TgLoadMonitor tgLoadMonitor : result){
            tgLoadMonitor.setDate(tgLoadMonitor.getDataDt());
        }
        return R.ok(result);
    }

    @NotNull
    private static List<TgLoadMonitor> getTgLoadMonitors(List<TgLoadMonitor> list) {
        Map<String, List<TgLoadMonitor>> meterIdMap = list.stream().collect(Collectors.groupingBy(TgLoadMonitor::getMeterId));
        List<TgLoadMonitor> result = new ArrayList<>();
        meterIdMap.forEach((key, value) -> {
            int previousOrder = 0;
            value.sort(Comparator.comparingInt(TgLoadMonitor::getTime));
            List<TgLoadMonitor> continuousGroup = new ArrayList<>();
            for (TgLoadMonitor tgLoadMonitor : value) {
                if (tgLoadMonitor.getTime() == previousOrder + 1 || continuousGroup.isEmpty()) {
                    continuousGroup.add(tgLoadMonitor);
                    previousOrder = tgLoadMonitor.getTime();
                } else {
                    // 如果当前记录不连续，则添加之前的连续段的最后一项
                    if (!continuousGroup.isEmpty()) {
                        result.add(continuousGroup.get(continuousGroup.size() - 1));
                    }
                    continuousGroup.clear();
                    continuousGroup.add(tgLoadMonitor);
                    previousOrder = tgLoadMonitor.getTime();
                }
            }
            // 添加最后一段连续记录的最后一项（如果有）
            if (!continuousGroup.isEmpty()) {
                result.add(continuousGroup.get(continuousGroup.size() - 1));
            }
        });
        if(CollectionUtils.isNotEmpty(result)){
            result.forEach(tgLoadMonitor -> {
                tgLoadMonitor.setStdOrgNm(OrgUtil.getStdOrgNm(tgLoadMonitor.getStdOrgNm()));
            });
        }
        return result;
    }

}
